package com.rabbitmq.demo;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @ClassName Producer
 * @Description 直连交换机生产者
 * @Author Kx
 * @Date 2025/10/10 10:29
 * @Version 1.0
 */
public class Producer {
    /**
     * 定义 direct(直连交换机）类型的交换机名称
     */
    private final static String EXCHANGE_NAME = "my.direct";

    /**
     * 指定路由key
     */
    private final static String ROUTER_KEY = "my.key";

    /**
     * 连接工厂
     */
    private static ConnectionFactory connectionFactory;

    /**
     * @author: kx
     * @date: 2025/10/10 10:36
     * @param null
     * @return
     * @description: 初始化工厂
    */
    static {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("kx");
        connectionFactory.setPassword("123456");
    }

    /**
     * @author: kx
     * @date: 2025/10/10 10:33
     * @param message : 消息内容
     * @description: 发送消息
    */
    public static void send(String message) {
        // 创建连接和通信通道
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()) {

            // 创建交换机并指定类型
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            // 发送信息给交换机
            // 参数一：交换机名称
            // 参数二：路由key
            // 参数三：交换机的其他属性设置
            // 参数四：消息内容(二进制)
            channel.basicPublish(EXCHANGE_NAME, ROUTER_KEY, null, message.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("操作失败" + e);
        }
    }

    public static void main(String[] args) {
        send("Hello world!");
    }
}
